<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!-- <el-input
        v-model="listQuery.name"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入服务名称"
      />
      <el-button
        v-permission="['article:articleClass:page']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter">查找
      </el-button> -->
      <el-button
        v-permission="['article:articleClass:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate">添加
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      :data="tableData"
      :tree-props="{ children: 'children' }"
      row-key="id"
      style="width: 100%;margin-bottom: 20px;"
      border>
      <el-table-column align="center" prop="name" label="服务名称" />
      <el-table-column align="center" prop="imgUrl" label="服务logo">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.imgUrl" height="230">
            <img slot="reference" :src="scope.row.imgUrl" height="23">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" label="服务内容" prop="serviceContent">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="showDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['article:articleClass:edit']"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button
            v-permission="['article:articleClass:delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList" />
    <!-- 查看服务内容对话框 -->
    <el-dialog :visible.sync="detailDialogVisible" title="服务内容" width="600px" style="text-align: center;">
      <div class="contentRecord" v-html="serviceContent" />
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="800px">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="right"
        label-width="100px"
        style="margin-right:20px;margin-bottom: -40px;">
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务名称" prop="name">
              <el-input v-model="dataForm.name" style="width: 240px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级" prop="pid">
              <el-select v-model="dataForm.pid" placeholder="请选择">
                <el-option v-for="(item, index) in levelList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="服务logo" prop="imgUrl">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeFileUplod"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .png, .gif">
            <img v-if="dataForm.imgUrl" ref="adImg" :src="dataForm.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="服务内容" prop="serviceContent">
          <editor :init="editorInit" v-model="dataForm.serviceContent" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listService, createService, updateService, deleteService } from '@/api/service'
import { uploadPath, beforeFileUplod, createStorage } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Editor from '@tinymce/tinymce-vue'
export default {
  name: 'Service',
  components: { Pagination, Editor },
  data() {
    return {
      listLoading: true,
      total: 0,
      serviceContent: '',
      textMap: { update: '编辑', create: '创建' },
      dialogStatus: '',
      uploadPath,
      beforeFileUplod,
      dialogFormVisible: false,
      dataForm: {
        imgUrl: undefined,
        name: undefined,
        serviceContent: undefined
      },
      tableData: [],
      levelList: [],
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      rules: {
        name: [{ required: true, message: '服务名称不能为空', trigger: 'change' }],
        imgUrl: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        serviceContent: [{ required: true, message: '请填写内容', trigger: 'blur' }],
        pid: [{ required: true, message: '请选择等级', trigger: 'blur' }]
      },
      detailDialogVisible: false,
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        ADMINTOKEN: getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      this.listLoading = true
      listService(this.listQuery).then(response => {
        console.log(response, 777)
        this.tableData = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
        this.getLevelList()
      })
        .catch(() => {
          this.total = 0
          this.listLoading = false
        })
    },
    // 获取等级选择框
    getLevelList() {
      this.levelList = []
      for (var i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].pid === 0) {
          this.levelList.push({ 'label': '父级', 'value': 0 }, { 'label': this.tableData[i].name, 'value': this.tableData[i].id })
        }
      }
      // 去重
      for (var a = 0; a < this.levelList.length; a++) {
        for (var b = a + 1; b < this.levelList.length; b++) {
          if (this.levelList[a].label === this.levelList[b].label) {
            this.levelList.splice(b, 1)
            b--
          }
        }
      }
    },
    // 查找
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 清空弹窗数据
    resetForm() {
      this.dataForm = {
        name: '',
        imgUrl: '',
        serviceContent: ''
      }
    },
    // 添加按钮
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.resetForm()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑按钮
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.dataForm = row
    },
    // 添加的确定按钮
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          var lis = []
          for (var i = 0; i < this.tableData.length; i++) {
            if (this.dataForm.name === this.tableData[i].name) {
              lis.push(i)
              this.$message.error('该服务名称已存在')
              break
            }
            if (this.tableData[i].children.length > 0) {
              for (var j = 0; j < this.tableData[i].children.length; j++) {
                if (this.dataForm.name === this.tableData[i].name || this.dataForm.name === this.tableData[i].children[j].name) {
                  lis.push(i)
                  this.$message.error('该服务名称已存在')
                  break
                }
              }
            }
          }
          if (lis.length === 0) {
            createService(this.dataForm)
              .then(response => {
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
                this.getList()
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        }
      })
    },
    // 编辑的确定按钮
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateService(this.dataForm)
            .then(() => {
              for (const v of this.tableData) {
                if (v.id === this.dataForm.id) {
                  const index = this.tableData.indexOf(v)
                  this.tableData.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新用户成功'
              })
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },

    handleDelete(row) {
      this.$confirm('此操作将删除 ' + row.name + ' , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteService(row.id).then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          this.getList()
        })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      })
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.dataForm.imgUrl = res.url
    },
    // 查看服务内容按钮
    showDetail(row) {
      this.detailDialogVisible = true
      this.serviceContent = row.serviceContent
    }
  }
}
</script>

<style lang="scss" scoped>
.contentRecord {
  ::v-deep img {
    width: 100%;
  }
}

.el-dialog {
  -webkit-box-shadow: none !important;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>
